package cn.wizzer.app.web.commons.utils;

import cn.wizzer.app.sys.modules.models.Sys_role;
import cn.wizzer.app.sys.modules.models.Sys_user;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpression;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.Strings;
import org.nutz.mvc.Mvcs;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by wizzer on 2018/3/17.
 */
@IocBean
public class StringUtil {
    /**
     * 获取平台当前登录用户的所在单位
     *
     * @return
     */
    public static String getPlatformUserUnitid() {
        try {
            Subject subject = SecurityUtils.getSubject();
            if (subject != null) {
                Sys_user user = (Sys_user) subject.getPrincipal();
                if (user != null) {
                    return Strings.sNull(user.getUnitid());
                }
            }
        } catch (Exception e) {

        }
        return "";
    }

    /**
     * 获取平台后台登录UID
     *
     * @return
     */
    public static Sys_user getPlatformUser() {
        try {
            HttpServletRequest request = Mvcs.getReq();
            if (request != null) {
                return (Sys_user) request.getSession(true).getAttribute("platform_user");
            }
        } catch (Exception e) {

        }
        return null;
    }
    /**
     * 获取平台后台登录UID
     *
     * @return
     */
    public static String getPlatformUid() {
        try {
            HttpServletRequest request = Mvcs.getReq();
            if (request != null) {
                return Strings.sNull(request.getSession(true).getAttribute("platform_uid"));
            }
        } catch (Exception e) {

        }
        return "";
    }

    /**
     * 获取平台后台登录用户名称
     *
     * @return
     */
    public static String getPlatformLoginname() {
        try {
            HttpServletRequest request = Mvcs.getReq();
            if (request != null) {
                return Strings.sNull(request.getSession(true).getAttribute("platform_loginname"));
            }
        } catch (Exception e) {

        }
        return "";
    }

    /**
     * 获取平台后台登录用户名称
     *
     * @return
     */
    public static String getPlatformUsername() {
        try {
            HttpServletRequest request = Mvcs.getReq();
            if (request != null) {
                return Strings.sNull(request.getSession(true).getAttribute("platform_username"));
            }
        } catch (Exception e) {

        }
        return "";
    }

    /**
     * 去掉URL中?后的路径
     *
     * @param p
     * @return
     */
    public static String getPath(String p) {
        if (Strings.sNull(p).contains("?")) {
            return p.substring(0, p.indexOf("?"));
        }
        return Strings.sNull(p);
    }

    /**
     * 获得父节点ID
     *
     * @param s
     * @return
     */
    public static String getParentId(String s) {
        if (!Strings.isEmpty(s) && s.length() > 4) {
            return s.substring(0, s.length() - 4);
        }
        return "";
    }

    /**
     * 得到n位随机数
     *
     * @param s
     * @return
     */
    public static String getRndNumber(int s) {
        Random ra = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s; i++) {
            sb.append(String.valueOf(ra.nextInt(8)));
        }
        return sb.toString();
    }

    /**
     * 判断是否以字符串开头
     *
     * @param str
     * @param s
     * @return
     */
    public boolean startWith(String str, String s) {
        return Strings.sNull(str).startsWith(Strings.sNull(s));
    }

    /**
     * 判断是否包含字符串
     *
     * @param str
     * @param s
     * @return
     */
    public boolean contains(String str, String s) {
        return Strings.sNull(str).contains(Strings.sNull(s));
    }

    /**
     * 将对象转为JSON字符串（页面上使用）
     *
     * @param obj
     * @return
     */
    public String toJson(Object obj) {
        return Json.toJson(obj, JsonFormat.compact());
    }
    /**
     * 将对象中的空字符串换位null
     *
     * @param source
     * @return
     */
    public static <T> T setNullValue(T source){
        T sources = source;
        try {
            Field[] fields = source.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (field.getGenericType().toString().equals(
                        "class java.lang.String")) {
                    field.setAccessible(true);
                    Object obj = field.get(source);
                    if (obj != null && obj.equals("")) {
                        field.set(source, null);
                    } else if (obj != null) {
                        String str = obj.toString();
                        str = StringEscapeUtils.escapeSql(str);//StringEscapeUtils是commons-lang中的通用类
                        field.set(source, str
                                //.replace("\\", "\\" + "\\")
                                //.replace("(", "\\(").replace(")", "\\)")
                                .replace("%", "\\%")
                                //.replace("*", "\\*")
                                //.replace("[", "\\[")
                                //.replace("]", "\\]")
                                //.replace("|", "\\|")
                                //.replace(".", "\\.")
                                .replace("$", "\\$")
                                //.replace("+", "\\+")
                                .trim()
                        );
                    }
                }
            }
        }catch(Exception e){
            return sources;
        }
        return source;
    }


    public static String getDict(String val, Map map) {
        if (StringUtils.isNotBlank(val)) {
            String[] str = val.split(",");
            String strname = "";
            for (int a = 0; a < str.length; a++) {
                strname += map.get(str[a]);
/*                if (strname == null) {
                    strname = "";
                }*/
                if (a < (str.length - 1)) {
                    strname += "/";
                }
            }
            return strname;
        }
        return "";
    }

    /**
     * 数据范围过滤
     *
     * @param userAlias 别名
     */
    public static String dataScopeFilter(String userAlias)
    {
        StringBuilder sqlString = new StringBuilder();
        Sys_user user = getPlatformUser();
        if(StringUtils.isNotBlank(userAlias)){
            userAlias = userAlias+".";
        }else {
            userAlias="";
        }
        for (Sys_role role : user.getRoles())
        {
            String dataScope = role.getDataScope();
            String units = "";
            if(StringUtils.isNotBlank(role.getUnits())){
                units = "'"+Arrays.stream(role.getUnits().split(",")).collect(Collectors.joining("','"))+"'";
            }else{
                //units=user.getUnitid();
            }
            if ("1".equals(dataScope))
            {
                //全部数据
                sqlString.append(" OR   1=1 ");
            }
            else if ("2".equals(dataScope))
            {
                sqlString.append(" OR   "+userAlias+"opBy IN ( SELECT id FROM sys_user WHERE unitid in ("+units+") ) ");
            }
            else if ("3".equals(dataScope))
            {
                sqlString.append(" OR   "+userAlias+"opBy in ( SELECT id FROM sys_user WHERE unitid = '"+user.getUnitid()+"' )  ");
            }
            else if ("4".equals(dataScope))
            {
                sqlString.append(" OR   "+userAlias+"opBy = '"+user.getId()+"' ");

            }
        }
        if(StringUtils.isNotBlank(sqlString)){
            sqlString = new StringBuilder(" AND ( "+sqlString.substring(4)+" ) ");
        }
        return sqlString.toString();
    }

    public static List<String> dataScopeUserCnd()
    {
        Sys_user user = StringUtil.getPlatformUser();
        int type = 5;
        List<String> unitss = null;
        for (Sys_role role : user.getRoles())
        {
            String dataScope = role.getDataScope();
            if(type<Integer.valueOf(dataScope)){
                break;
            }
            type = Integer.valueOf(dataScope);
            if ("1".equals(dataScope))
            {
                unitss=new ArrayList<>();
            }
            else if ("2".equals(dataScope))
            {
                if(StringUtils.isNotBlank(role.getUnits())){
                    unitss=Arrays.stream(role.getUnits().split(",")).collect(Collectors.toList());
                }
            }
            else if ("3".equals(dataScope))
            {
                unitss=new ArrayList<>();
                unitss.add(user.getUnitid());
            }
            else if ("4".equals(dataScope))
            {
                unitss=new ArrayList<>();
                unitss.add(user.getUnitid());
            }
        }
        return unitss;
    }


    /**
     * 数据范围过滤
     *
     * @param userAlias 别名
     */
    public static String dataScopeFilterJyksBh(String userAlias,String type)
    {
        StringBuilder sqlString = new StringBuilder();
        Sys_user user = getPlatformUser();
        if(StringUtils.isNotBlank(userAlias)){
            userAlias = userAlias+".";
        }else {
            userAlias="";
        }
        for (Sys_role role : user.getRoles())
        {
            String dataScope = role.getDataScope();
            if ("1".equals(dataScope))
            {
                //全部数据
                sqlString.append(" OR   1=1 ");
            }
            if ("2".equals(dataScope))
            {
                if(StringUtils.isNotBlank(role.getUnits())){
                    for(String unitid :role.getUnits().split(",")){
                        sqlString.append(" OR   "+userAlias+type+" like '%"+unitid+"%' ");
                    }
                }
            }
            if ("3".equals(dataScope))
            {
                sqlString.append(" OR   "+userAlias+type+" like '%"+StringUtil.getPlatformUserUnitid()+"%' ");
            }
            if ("4".equals(dataScope))
            {
                sqlString.append(" OR   "+userAlias+"opAt = '"+StringUtil.getPlatformUid()+"' ");
            }
        }
        if(StringUtils.isNotBlank(sqlString)){
            sqlString = new StringBuilder(" AND ( "+sqlString.substring(4)+" ) ");
        }
        return sqlString.toString();
    }

    /**
     * 数据范围过滤
     *
     * @param userAlias 别名
     */
    public static String dataScopeReportJyksBh(String userAlias,String type)
    {
        StringBuilder sqlString = new StringBuilder();
        Sys_user user = getPlatformUser();
        if(StringUtils.isNotBlank(userAlias)){
            userAlias = userAlias+".";
        }else {
            userAlias="";
        }
        for (Sys_role role : user.getRoles())
        {
            String dataScope = role.getDataScope();
            if ("1".equals(dataScope))
            {
                //全部数据
                sqlString.append(" OR   1=1 ");
            }
            if ("2".equals(dataScope))
            {
                if(StringUtils.isNotBlank(role.getUnits())){
                    for(String unitid :role.getUnits().split(",")){
                        sqlString.append(" OR   "+userAlias+type+" like '%"+unitid+"%' ");
                    }
                }
            }
            if ("3".equals(dataScope))
            {
                sqlString.append(" OR   "+userAlias+"opBy in ( SELECT id FROM sys_user WHERE unitid = '"+user.getUnitid()+"' )  ");
                sqlString.append(" OR   "+userAlias+type+" like '%"+StringUtil.getPlatformUserUnitid()+"%' ");
            }
            if ("4".equals(dataScope))
            {
                sqlString.append(" OR   "+userAlias+"opBy = '"+StringUtil.getPlatformUid()+"' ");
                sqlString.append(" OR   "+userAlias+type+" like '%"+StringUtil.getPlatformUserUnitid()+"%' ");
            }
        }
        if(StringUtils.isNotBlank(sqlString)){
            sqlString = new StringBuilder(" AND ( "+sqlString.substring(4)+" ) ");
        }
        return sqlString.toString();
    }


    /**
     * 数据范围过滤
     *
     * @param userAlias 别名
     */
    public static String dataScopeFilter(Sys_user user,String userAlias)
    {
        StringBuilder sqlString = new StringBuilder();
        if(StringUtils.isNotBlank(userAlias)){
            userAlias = userAlias+".";
        }
        for (Sys_role role : user.getRoles())
        {
            String dataScope = role.getDataScope();
            String units = "";
            if(StringUtils.isNotBlank(role.getUnits())){
                units = "'"+Arrays.stream(role.getUnits().split(",")).collect(Collectors.joining("','"))+"'";
            }else{
                //units=user.getUnitid();
            }
            if (StringUtils.isNotBlank(userAlias))
            {
                if ("1".equals(dataScope))
                {
                    //全部数据
                    sqlString.append(" OR   1=1 ");
                }
                else if ("2".equals(dataScope))
                {
                    sqlString.append(" OR   "+userAlias+"opBy IN ( SELECT id FROM sys_user WHERE unitid in ("+units+") ) ");
                }
                else if ("3".equals(dataScope))
                {
                    sqlString.append(" OR   "+userAlias+"opBy in ( SELECT id FROM sys_user WHERE unitid = '"+user.getUnitid()+"' )  ");
                }
                else if ("4".equals(dataScope))
                {
                    sqlString.append(" OR   "+userAlias+"opBy = '"+user.getId()+"' ");

                }

            }
        }
        if(StringUtils.isNotBlank(sqlString)){
            sqlString = new StringBuilder(" AND ( "+sqlString.substring(4)+" ) ");
        }
        return sqlString.toString();
    }
}
